package com.jamal2362.apktool.task;

import android.content.Context;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.view.View;
import android.widget.TextView;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import com.jamal2362.apktool.R;
import com.jamal2362.apktool.util.Apkinfo;
import com.jamal2362.apktool.util.Colors;
import com.jamal2362.apktool.util.FileUtils;
import com.jamal2362.apktool.util.MUtil;
import com.jamal2362.apktool.util.Settings;
import com.jamal2362.apktool.util.TextUtil;

public class FileSizeTask extends AsyncTask<File, Integer, List<String>> {
	private TextView textView;
	private Context context;
	private String tviewTag;
	private boolean highLight;

	public FileSizeTask(Context ctx, TextView tview, boolean hl) {
		this.context = ctx;
		this.textView = tview;
		this.textView.setText("...");
		this.tviewTag = tview.getTag().toString();
		this.highLight = hl;
	}

	@Override
    protected List<String> doInBackground(File... parameter) {
		int pos = 0;
		File mFile = parameter[0];
		boolean isdir = mFile.isDirectory();
		long time = mFile.lastModified();
		List<String> res = new ArrayList<String>();
		res.add(pos++, TextUtil.dateFormat(time));
		if ((Settings.folderSize && isdir) || !isdir) {
			long fSize = FileUtils.getFileSize(mFile);
			res.add(pos++, FileUtils.humanReadableByteCount(fSize, false));
		}
		if (mFile.getName().endsWith(".apk")) {
			Apkinfo info = new Apkinfo(context, mFile);
			if (info.isValid())
				res.add(pos++, "v" + info.version() + "(" + info.code() + ")");
		}
		if (isdir) {
			try {
				res.add(pos++, context.getString(R.string.foldersc) + ": " + FileUtils.countOfFiles(context, mFile, true));
				res.add(pos++, context.getString(R.string.filesc) + ": " + FileUtils.countOfFiles(context, mFile, false));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return res;
    }

	@Override
    protected void onPostExecute(List<String> result) {
		if (!textView.getTag().toString().equals(tviewTag))
			return;
		String fileDetails = MUtil.strJoin(result.toArray(new String[0]), ", ");
		if (highLight) {
			SpannableString spanFileName = new SpannableString(fileDetails);
			spanFileName.setSpan(new ForegroundColorSpan(Colors.DARK_GREEN), 0, fileDetails.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			spanFileName.setSpan(new StyleSpan(Typeface.BOLD), 0, fileDetails.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			textView.setText(spanFileName);
		} else {
			textView.setText(fileDetails);
		}
		textView.setVisibility(View.VISIBLE);
    }
}
